using System;
using CUtil;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace CStock
{
	/// <summary>
	/// Summary description for TradeSystem.
	/// </summary>
	/// 
	[Serializable] 
	public class TradeSystem : TradeSystemBase, ITradeSystem
	{
		#region pivate Data

        
        private string portfolioID;
        //private double money_ForSystem;
        string shareID;
       
        private double valueMoney;
		
        //private double bestPerformance;
        //private double bestRelativePerformance;
        //private string[] bestParameters;
        protected int numberOfItemsAvailable;


        protected TradeStatus tradeStatus;

	

		private System.Collections.ArrayList tradeEvents;


        //Public NoSellConditionsToFulfill As Integer
		#endregion

		#region constructor
		public TradeSystem()
		{
            this.tradeStatus = TradeStatus.Unknown;
			tradeEvents = new System.Collections.ArrayList();
			optimizationResults = new List<IOptimizationResult>();
			
		}

		#endregion

		#region public properties

        public ITradeSystem Copy()
        {
            TradeSystem ts = new TradeSystem();
            ts.Name = this.Name;
            ts.BuyConditionsCollection = new ArrayList();
            for (int i = 0; i < this.BuyConditionsCollection.Count; i++)
            {
                ITradeCondition tc = this.BuyConditionsCollection[i] as ITradeCondition;

                ts.BuyConditionsCollection.Add(tc.Copy());
            }
            ts.SellConditionsCollection = new ArrayList();
            for (int i = 0; i < this.SellConditionsCollection.Count; i++)
            {
                ITradeCondition tc = this.SellConditionsCollection[i] as ITradeCondition;
                ts.SellConditionsCollection.Add(tc.Copy());
            }
            ts.OptimizationResults = new List<IOptimizationResult>();
            for (int i = 0; i < this.OptimizationResults.Count; i++)
            {
                ts.OptimizationResults.Add(this.OptimizationResults[i]);
            }

            //ts.SellConditionsCollection = this.SellConditionsCollection;
            //ts.optimizationResultsCollection = this.OptimizationResultsCollection;
            return ts;

        }


		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public override string ID
		{
			get
			{
				
				return this.iD;
			}
			set
			{
				this.iD = value;
				if(this.iD != null && this.iD != string.Empty)
				{
					this.path = ProgramContext.Instance.Configuration.Directories.TradeSystemsTemplatesPath ;
                    
				}
			}
		}
        public static System.Collections.ArrayList GetTradeSystemTemplates()
        {
            System.Collections.ArrayList tradeSystems = new System.Collections.ArrayList();
            System.Collections.ArrayList arrFiles = CUtil.DirectoryUtil.GetXMLFiles(ProgramContext.Instance.Configuration.Directories.TradeSystemsTemplatesPath);
            for (int i = 0; i < arrFiles.Count; i++)
            {
                string str = arrFiles[i] as string;
                tradeSystems.Add(CStock.TradeSystem.GetTradeSystemTemplate(ProgramContext.Instance.Configuration.Directories.TradeSystemsTemplatesPath + "\\" + str));

            }
            return tradeSystems;
        }
		public static TradeSystem GetTradeSystemTemplate(string MyFullFilePath)
		{
            TradeSystem MytradeSystem = null;
            try
            {
                object o = new TradeSystem();


                //-----------------------
                //Search for trade system file

                if (System.IO.File.Exists(MyFullFilePath))
                {
                    //if(! System.Environment.UserInteractive)
                    XMLSerializable.DeSerializeObject(ref o, MyFullFilePath);
                    MytradeSystem = o as TradeSystem;

                    if (MytradeSystem == null)
                    {
                        System.Windows.Forms.MessageBox.Show("Default TradeSystem file " + MyFullFilePath + " could not be opened");
                    }

                }
                
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Could not get Trade system " + MyFullFilePath + "; " + ex.Message);
            }
            return MytradeSystem;

		}

		public OptimizationResult[] OptimizationResultsArray
		{
			get
			{
                if (optimizationResults != null)
                {
                    List<IOptimizationResult> loptim = optimizationResults as List<IOptimizationResult>;
                    if (loptim.Count > 0)
                    {
                        return (OptimizationResult[])loptim.ToArray();
                    }
                    return null;
                }
                return null;
			}
			
	
		}


      

		#endregion
		
		#region saving

		public bool Serialize_AsTradeResult(string MyShareID)
		{
			
			string strPath = ProgramContext.Instance.Configuration.Directories.TradeSystemsTemplatesPath;

			string[] dirs = System.IO.Directory.GetDirectories(strPath  ,"*.*");


			bool bfound = false;
			for(int i = 0;i < dirs.Length; i++)
			{
				if(dirs[i] == MyShareID)
				{
					bfound = true;
					break;
				}
			}

			if(!bfound)
			{
				System.IO.Directory.CreateDirectory(strPath + "\\TradeSystems\\"  + MyShareID );
			}

			
			XMLSerializable.SerializeObject(this,strPath + "\\TradeSystems\\"  + MyShareID + "\\" + this.Name + ".xml");

			return true;
			
		}
		#endregion

		#region CopyConstructor - only for serializing !!

	

		#endregion

        #region ITradeSystemItem Members

      

        public string PortfolioID
        {
            get
            {
                return this.portfolioID;
            }
            set
            {
                portfolioID = value;
            }
        }

        public double Value_Total
        {
            get
            {
                return this.valueMoney + Value_Shares;
            }

        }
        public double Value_Shares
        {
            get
            {
                IDataClass dc = TradeEconomy.GetShareByID(shareID);
                Debug.Assert(dc != null, "SW Error - no data class set for TradeSystem");
                double quc = dc.QuoteCurrent;
                Debug.Assert(quc != 0F, "SW Error - no quote for data class");

                double f = numberOfItemsAvailable * quc;
                return f;

                
            }

        }
        public double Value_Money
        {
            get
            {
                return this.valueMoney;
            }
            set
            {
                valueMoney = value;
            }

        }
        public int NumberOfItemsAvailable
        {
            get
            {
                return this.numberOfItemsAvailable;
            }
            set
            {
                numberOfItemsAvailable = value;
            }

        }

   

        public string ShareID
        {
            get
            {
                return shareID;
            }
            set
            {
                shareID = value;
            }
        }

        public double Performance
        {
            get
            {
                return 0f;

            }
        }

        public double PerformancePerYear
        {
            get
            {
                return 0f;
            }
        }
        public TradeStatus TradeStatus
        {
            get
            {
                return this.tradeStatus;
            }
            set
            {
                this.tradeStatus = value;
            }
        }
        

        #endregion

        #region obsolete

        //double percentageMoney;
        //double percentageBonds;
        //double percentageShares;

        //int trades_Shares;
        //int trades_Bonds;
        //int numberOfTradesPerYear;
        ////[Category("Trade\\Decimal"), DescriptionAttribute("Decimal")]
        ////        [Category("DataTypes\\Boolean"), DescriptionAttribute("Boolean")]
        //[Category("Trade\\Percentage"), DescriptionAttribute("double")]
        //public double PercentageMoney
        //{
        //    get
        //    {
        //        return percentageMoney;
        //    }
        //    set
        //    {
        //        percentageMoney = value;
        //    }
        //}

        //[Category("Trade\\Percentage"), DescriptionAttribute("double")]
        //public double PercentageShare
        //{
        //    get
        //    {
        //        return percentageShares;
        //    }
        //    set
        //    {
        //        percentageShares = value;
        //    }
        //}

        //[Category("Trade\\Percentage"), DescriptionAttribute("double")]
        //public double PercentageBonds
        //{
        //    get
        //    {
        //        return percentageBonds;
        //    }
        //    set
        //    {
        //        percentageBonds = value;
        //    }
        //}

        //[Category("Trade\\Behaviour"), DescriptionAttribute("int")]
        //public int Trades_Shares
        //{
        //    get
        //    {
        //        return trades_Shares;
        //    }
        //    set
        //    {
        //        trades_Shares = value;
        //    }
        //}
        //[Category("Trade\\Behaviour"), DescriptionAttribute("int")]
        //public int Trades_Bonds
        //{
        //    get
        //    {
        //        return trades_Bonds;
        //    }
        //    set
        //    {
        //        trades_Bonds = value;
        //    }
        //}
        ////for specifying intraday trader (greater than 200)
        //[Category("Trade\\Behaviour"), DescriptionAttribute("int")]
        //public int NumberOfTradesPerYear
        //{
        //    get
        //    {
        //        return this.numberOfTradesPerYear;
        //    }
        //    set
        //    {
        //        numberOfTradesPerYear = value;
        //    }
        //}

        //public bool SetProfile_Mention(int myTradeBonds, int myTradeShares,
        //    int myPercentageShare, int myPercentageBonds, int myPercentageMoney, ITradeSystem myTradeSystem, int myNumberOfTradesPerYear)
        //{

        //    this.trades_Bonds = myTradeBonds;
        //    this.trades_Shares = myTradeShares;
        //    this.percentageBonds = myPercentageBonds;
        //    this.percentageShares = myPercentageShare;
        //    this.percentageMoney = myPercentageMoney;
        //    this.numberOfTradesPerYear = myNumberOfTradesPerYear;
        //    return true;

        //}
        ////half of the traders are intraday
        //public bool SetProfile_Simple()
        //{

        //    this.trades_Bonds = 100;
        //    this.trades_Shares = 100;
        //    this.percentageBonds = 40;
        //    this.percentageShares = 40;
        //    this.percentageMoney = 100 - this.percentageShares - this.percentageBonds;

        //    double randomNumber = RandomGenerator.Random(0, 1);
        //    if (randomNumber > 0.5)
        //    {
        //        double randomN = RandomGenerator.Random(200, 100000);
        //        this.numberOfTradesPerYear = Convert.ToInt32(randomN);
        //    }
        //    else
        //    {
        //        double randomN = RandomGenerator.Random(1, 200);
        //        this.numberOfTradesPerYear = Convert.ToInt32(randomN);
        //    }


        //    return true;


        //}
        //public bool SetProfile_Random()
        //{

        //    Random temp = new Random();


        //    this.trades_Bonds = temp.Next(0, 250);
        //    this.trades_Shares = temp.Next(0, 250);
        //    this.percentageBonds = temp.Next(100);
        //    int percLeft = 100 - Convert.ToInt32(this.percentageBonds);
        //    this.percentageShares = temp.Next(percLeft);
        //    percLeft = 100 - Convert.ToInt32(this.percentageBonds);
        //    this.percentageMoney = 100 - this.percentageShares - this.percentageBonds;

        //    return true;

        //}

        #endregion


	}
}
